/*
 *   项目名称：rpc-demo
 *   文件名称：com.xiaolon.rpc.bootstrap.ProviderBootstrap
 *
 *   创建人：  ZHOU XIAO LONG
 *   创建日期：2024/12/11
 *
 */
package com.xiaolon.rpc.bootstrap;



import com.xiaolon.rpc.RpcApplication;
import com.xiaolon.rpc.config.RegistryConfig;
import com.xiaolon.rpc.config.RpcConfig;
import com.xiaolon.rpc.model.ServiceMetaInfo;
import com.xiaolon.rpc.model.ServiceRegisterInfo;
import com.xiaolon.rpc.registry.LocalRegistry;
import com.xiaolon.rpc.registry.Registry;
import com.xiaolon.rpc.registry.RegistryFactory;
import com.xiaolon.rpc.server.tcp.VertxTcpServer;

import java.util.List;

/*
 * 类描述：ProviderBootstrap
 * 服务提供者启动类
 */
public class ProviderBootstrap {

    /**
     * 初始化
     * @param serviceRegisterInfoList
     */
    public static void init(List<ServiceRegisterInfo<?>> serviceRegisterInfoList){
        // RPC框架初始化（配置和注册中心）
        RpcApplication.init();

        // 全局配置
        RpcConfig rpcConfig = RpcApplication.getRpcConfig();

        // 注册服务
        for (ServiceRegisterInfo<?> serviceRegisterInfo : serviceRegisterInfoList) {
            String serviceName = serviceRegisterInfo.getServiceName();
            // 本地注册
            LocalRegistry.registry(serviceName, serviceRegisterInfo.getImplClass());

            // 注册服务到注册中心
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());

            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceHost(rpcConfig.getHost());
            serviceMetaInfo.setServicePort(rpcConfig.getPort());
            try {
                registry.register(serviceMetaInfo);
            }catch (Exception e){
                throw new RuntimeException(serviceName + "服务注册失败");
            }
        }

        // 启动服务器
        VertxTcpServer vertxTcpServer = new VertxTcpServer();
        vertxTcpServer.doStart(rpcConfig.getPort());
    }
}
